<template>
  <div>
    <div class="login">
      <el-form
        :model="user"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlerLogin">登录</el-button>
          <el-button @click="handlerReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      user: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: this.pdwValidator, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    pdwValidator(rule, value, callback) {
      if (value.length < 5 || value.length > 8) {
        return callback(new Error("密码需要5-8位。。"));
      }
      callback();
    },
    handlerLogin() {
      this.$refs.ruleForm
        .validate()
        .then((value) => {
          // console.log(value,"登录成功");
          this.$message({
            message: "登录成功",
            type: "success",
            duration: 1000,
            onClose: () => {
              this.$router.push({
                name: "main",
              });
            },
          });
        }).catch((err) => {
          // console.log(err,"登录失败");
          this.$message({
            message: "登录失败，请修改错误信息！",
            type: "error",
            duration: 3000,
          });
        });
      // this.$refs.ruleForm.validate((valid) => {
      //   // 成功的验证
      //   if (valid) {
      //     alert("submit!");
      //   } else {
      //     // 失败的验证
      //     console.log("error submit!!");
      //     return false;
      //   }
      // });
    },
    handlerReset() {
      this.$refs.ruleForm.resetFields();
    },
  },
};
</script>
<style lang="less" scoped>
.login {
  width: 30vw;
  height: 20vh;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
